//
//  MantisRichTextModel.m
//  NLProjectFrameworkDemo
//
//  Created by iosdeveloper on 2020/8/19.
//  Copyright © 2020 yj_zhang. All rights reserved.
//

#import "MantisRichTextModel.h"
#import "MantisAcademicCellData.h"
#import "CommonHeader.h"


#define textViweWidth (IMSCREEN_WIDTH-leftSpaceMargin-rightSpaceMargin-20)

@class MantisTextCellConetentData;
@interface MantisRichTextModel()


@end

@implementation MantisRichTextModel
-(CGSize)contentSizefromMsg:(NSString*)msg{
    CGFloat height=0;
    // NSLog(@"初始化msg%@",msg);
    if (![msg containsString:@"additionMsg"]) {
        msg = [msg stringByReplacingOccurrencesOfString:@"webp" withString:@"png"];
        UITextView*textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, textViweWidth, 50)];
        textView.scrollEnabled = NO;

        NSString*content=[self getNEWNodefrom:msg];
        content = [content stringByAppendingString:@"\n"];
        CGFloat imgHeight = [self getImgHightfrom:msg];

        textView.attributedText=[self richStrFrom:msg];

        CGFloat texHeight = [self getSpaceLabelHeightwithSpeace:6 withFont:KIMFontRegularSize(16) withWidth:textViweWidth str:textView.text];

        height= texHeight+imgHeight;
    
        NSAttributedString*attriText = [self fromHtmlStr:msg];

        CGSize contentSize = [attriText boundingRectWithSize:CGSizeMake(textViweWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
        return CGSizeMake(contentSize.width, height);
        
    }else
    {
        NSDictionary*contentDic=self.historyModel.msg.mj_keyValues;
        MantisTextCellContentData*content=[MantisTextCellContentData mj_objectWithKeyValues:contentDic];
        NSInteger btnCount=content.content.count;
        NSInteger rowCount=btnCount/3+btnCount%3;
        
        CGFloat addHeight=adaptWidth750(52)*rowCount+(rowCount-1)*5;
        
        height+=addHeight;
        
        return  CGSizeMake(textViweWidth, height);
        
    }
    return  CGSizeMake(textViweWidth, height);
}

-(NSString*)getNEWNodefrom:(NSString*)str{
    
    //    NSLog(@"编码前%@",str);
    if (str.length>0) {
        OGNode *htmlData=[ObjectiveGumbo parseNodeWithString:str];
        NSString*htmlStr = htmlData.html;
        NSArray*textArr = [htmlStr componentsSeparatedByString:@"\n"];
        NSMutableArray*tempArr = [NSMutableArray new];
        
        for (NSString*divStr in textArr) {
            if (![divStr containsString:@"<"]) {//没有标签存到数组
                [tempArr addObject:divStr];
            }else
            {
                if ([divStr containsString:@"<img"]) {//有图片的标签存到数组
                    NSString*  newDivStr= [self getImgSrcStr:divStr];
                    NSMutableArray*divImgArr = [newDivStr componentsSeparatedByString:@" "].mutableCopy;
                    if (divImgArr.count>2) {
                        NSString*imgUrl =divImgArr [1];
                        
                        CGSize size =[self calculatePicHeight:imgUrl];
                        CGFloat imgWidth =size.width;
                        CGFloat imgHieght =size.height;
                        
                        
                        NSString*imgStyleStr = [NSString stringWithFormat:@"style=\"width:%f;height:%f\";>",imgWidth,imgHieght];
                        NSMutableArray*splitArr=[newDivStr componentsSeparatedByString:@" "].mutableCopy;
                        
                        NSMutableArray*newSplitArr = [NSMutableArray new];
                        [newSplitArr addObject:splitArr[0]];
                        [newSplitArr addObject:splitArr[1]];
                        [newSplitArr addObject:imgStyleStr];
                        NSString*newStr=[newSplitArr componentsJoinedByString:@" "];
                        [tempArr addObject:newStr];
                    }
                    
                }else{
                    // NSLog(@"过滤掉标签");
                }
            }
        }
        
        NSString*content=[tempArr componentsJoinedByString:@"\n"];
        NSLog(@"编辑后%@",content);
        return content;
    }
    
    return @"";
}

//通过图片url地址获取图片高度
-(CGSize)calculatePicHeight:(NSString*)divStr{
    
    NSString*newImgStr = [divStr stringByReplacingOccurrencesOfString:@"src=" withString:@""];//获取图片url地址
    newImgStr = [newImgStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];//获取图片url地址里面的引号
    
    CGSize size =[UIImage getImageSizeWithURL:newImgStr];
    
    CGFloat imgWidth =size.width;
    CGFloat imgHieght =size.height;
    CGFloat imgRate = imgHieght/imgWidth;
    if ([newImgStr containsString:@"emojiImg"]||[newImgStr containsString:@"emoji"]) {
        imgWidth =30;
        imgHieght=imgWidth;
        
    }else{
        if (imgWidth<1.0) {
               
           }else{
               if (imgWidth>textViweWidth) {
                   imgWidth=textViweWidth;
                   imgHieght =imgWidth*imgRate;
               }
           }
        
    }
    
    CGSize newSize = CGSizeMake(imgWidth, imgHieght);
    return newSize;
}

//通过图片url地址获取图片高度不包含表情高度
-(CGSize)noEmojcalculatePicHeight:(NSString*)divStr{
    
    NSString*newImgStr = [divStr stringByReplacingOccurrencesOfString:@"src=" withString:@""];//获取图片url地址
    newImgStr = [newImgStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];//获取图片url地址里面的引号
    
    CGSize size =[UIImage getImageSizeWithURL:newImgStr];
    
    CGFloat imgWidth =size.width;
    CGFloat imgHieght =size.height;
    CGFloat imgRate = imgHieght/imgWidth;
    if ([newImgStr containsString:@"emojiImg"]||[newImgStr containsString:@"emoji"]) {
        imgWidth =30;
        imgHieght=10;
        
    }else{
        if (imgWidth<1.0) {
               
           }else{
               if (imgWidth>textViweWidth) {
                   imgWidth=textViweWidth;
                   imgHieght =imgWidth*imgRate;
               }
           }
        
    }
    
    CGSize newSize = CGSizeMake(imgWidth, imgHieght);
    return newSize;
}
-(CGFloat)getImgHightfrom:(NSString*)str{
    
    if (str.length>0) {
        OGNode *htmlData=[ObjectiveGumbo parseNodeWithString:str];
        NSString*htmlStr = htmlData.html;
        NSArray*textArr = [htmlStr componentsSeparatedByString:@"\n"];
        CGFloat startHeight =0;
        
        for (NSString*divStr in textArr) {
            
            if ([divStr containsString:@"<img"]) {//有图片的标签存到数组
                NSString*newStr = [self getImgSrcStr:divStr];
                NSMutableArray*divImgArr = [newStr componentsSeparatedByString:@" "].mutableCopy;
                if (divImgArr.count>2) {
                    NSString*imgUrl =divImgArr [1];
                    CGSize size = [self noEmojcalculatePicHeight:imgUrl];
                    CGFloat imgHieght=size.height;
                    startHeight+=imgHieght;
                    
                }
                
            }
        }
        return startHeight;
    }
    return 0;
}
//计算文字高度
-(CGFloat)getSpaceLabelHeightwithSpeace:(CGFloat)lineSpeace withFont:(UIFont*)font withWidth:(CGFloat)width str:(NSString*)str{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    //    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    /** 行高 */
    paraStyle.lineSpacing = lineSpeace;
    // NSKernAttributeName字体间距
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle};
    CGSize size = [str boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

//把html标签转成富文本
-(NSAttributedString*)fromHtmlStr:(NSString*)html{

    NSData *data = [html dataUsingEncoding:NSUnicodeStringEncoding];
    
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSAttributedString *str = [[NSAttributedString alloc]initWithData:data

                                                               options:options

                                                    documentAttributes:nil

                                                                 error:nil];
    NSMutableAttributedString*asstr = [[NSMutableAttributedString alloc]initWithAttributedString:str];
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
       /** 行高 */
       paraStyle.lineSpacing = 6;
    NSDictionary *dic = @{NSFontAttributeName:KIMFontRegularSize(16), NSParagraphStyleAttributeName:paraStyle
                             };
    [asstr addAttributes:dic range:NSMakeRange(0, str.length)];
    
    

   return asstr;
}
//把后台返回的标签转为富文本
-(NSAttributedString *)richStrFrom:(NSString*)msg{
     msg = [msg stringByReplacingOccurrencesOfString:@"webp" withString:@"png"];
    NSString*str = [self getNEWNodefrom:msg];
    NSAttributedString*newStr = [self fromHtmlStr:str];
    
    return newStr;
}
//拿到src图片资源
-(NSString*)getImgSrcStr:(NSString*)orginalStr{
    NSArray*divImgArr = [orginalStr componentsSeparatedByString:@" "].mutableCopy;
    NSString*  newAllStr=@"";
    for (NSString*allStr in divImgArr) {
        if ([allStr containsString:@"src="]) {
             newAllStr = [@"<img " stringByAppendingFormat:@"%@ >",allStr];
            
        }
    }
    
    return newAllStr;
}







@end
